#include "BezierCurve.h"
#include "MyVertex.h"

namespace Curves
{
	using namespace CAD_CAM;

	BezierCurve::BezierCurve(void): Primitive(102*3+1,102), VerticesMax(102*3+1)
	{
		vertexVector.reserve(1000);
		bezierVertices = 10;
		build();
	}


	BezierCurve::~BezierCurve(void)
	{

	}

	void BezierCurve::build()
	{
		int ind = 2;
		for(int i=0; ind<indices; ++i)
		{
			indicesArray[ind-2] = i;
			indicesArray[ind-1] = i;
			indicesArray[ind] = i;

			ind += 3;
		}
	}

	void BezierCurve::addVertex( const QVector3D & v)
	{
		vertexVector.push_back(MyVertex(v));
		mVertexVBO.bind();
		mVertexVBO.allocate(vertexVector.data(), sizeof(MyVertex)*vertexVector.count());
		mVertexVBO.release();
	}

	void BezierCurve::removeVertex( int indx)
	{
		vertexVector.remove(indx);
		mVertexVBO.bind();
		mVertexVBO.allocate(vertexVector.data(), sizeof(MyVertex)*vertexVector.count());
		mVertexVBO.release();
	}

	void BezierCurve::DrawShader(QGLShaderProgram& shaderProgram, QMatrix4x4& viewMatrix, QMatrix4x4& projectionMatrix)
	{
		if(isInited == false)
			initBuffers();
		mVertexVBO.bind();
		mIndexVBO.bind();
	
		QMatrix4x4 modelMatrix;
		modelMatrix.translate(translation);
		modelMatrix.scale(sizeScale);

		shaderProgram.bind();

		int inPositionLocation[4];
		inPositionLocation[0] = shaderProgram.attributeLocation("inPosition0");
		inPositionLocation[1] = shaderProgram.attributeLocation("inPosition1");
		inPositionLocation[2] = shaderProgram.attributeLocation("inPosition2");
		inPositionLocation[3] = shaderProgram.attributeLocation("inPosition3");
		int inColorLocation = shaderProgram.attributeLocation("inColor");

		int inModelMatrixLocation = shaderProgram.uniformLocation("inModelMatrix");
		int inViewMatrixLocation = shaderProgram.uniformLocation("inViewMatrix");
		int inProjectionMatrixLocation = shaderProgram.uniformLocation("inProjectionMatrix");
		int inVerticesLocation = shaderProgram.uniformLocation("inVertices");

		for(int i = 0; i<4; ++i)
		{
			shaderProgram.enableAttributeArray(inPositionLocation[i]);
			shaderProgram.setAttributeBuffer(inPositionLocation[i], GL_FLOAT, i * sizeof(MyVertex), 3, sizeof(MyVertex) * 3);
		}

		shaderProgram.enableAttributeArray(inColorLocation);
		shaderProgram.setAttributeBuffer(inColorLocation, GL_FLOAT, 12, 3, sizeof(MyVertex) * 3);
		shaderProgram.setUniformValue(inModelMatrixLocation, modelMatrix);
		shaderProgram.setUniformValue(inViewMatrixLocation, viewMatrix);
		shaderProgram.setUniformValue(inProjectionMatrixLocation, projectionMatrix);
	
		shaderProgram.setUniformValue(inVerticesLocation, vertexVector.count());

		glDrawElements(GL_POINTS, indices * 3, GL_UNSIGNED_INT, 0);

		for(int i = 0; i<4; ++i)
		{
			shaderProgram.disableAttributeArray(inPositionLocation[i]);
		}
    
		shaderProgram.disableAttributeArray(inColorLocation);
	
		shaderProgram.release();
	
		mVertexVBO.release();
		mIndexVBO.release();
	}
}